﻿using System;
using System.Linq;
using System.Web.Mvc;

using MusicStore.Domain.Concrete;
using MusicStore.Domain.POCO;

using MusicStore.WebUI.Models;

namespace MusicStore.WebUI.Controllers
{
    [Authorize]
    public class CheckoutController : Controller
    {
        EFDbContext storeDB = new EFDbContext();
        const string PromoCode = "FREE";

        //
        // GET: /Checkout/AddressAndPayment

        public ActionResult AddressAndPayment()
        {
            ShoppingCartManager manager = new ShoppingCartManager();
            
            ShoppingCart cart = manager.GetShoppingCartWithCartItems(Session[ShoppingCartController.CTE_Session_UserName].ToString());
            if (cart == null) return RedirectToAction("Index", "ShoppingCart");

            return View();
        }

        //
        // POST: /Checkout/AddressAndPayment

        [HttpPost]
        public ActionResult AddressAndPayment(FormCollection values)
        {
            ShoppingCartManager manager = new ShoppingCartManager();
            if (manager.MigrateCart(Session[ShoppingCartController.CTE_Session_UserName].ToString(), User.Identity.Name))
            {
              Order newOrder = new Order();
              TryUpdateModel(newOrder);

              newOrder.Username = User.Identity.Name;
              newOrder.OrderDate = DateTime.Now;

              //Process the order
              manager.FillOrderWithShoppingCardInfo(newOrder);

              //Save Order
              storeDB.Orders.Add(newOrder);
              storeDB.SaveChanges();

              manager.DeleteShoppingCartOfUser(newOrder.Username);

              return RedirectToAction("Complete", new { id = newOrder.OrderId });
            }

            return RedirectToAction("Index", "ShoppingCart");
        }

        //
        // GET: /Checkout/Complete

        public ActionResult Complete(int id)
        {
            // Validate customer owns this order
            bool isValid = storeDB.Orders.Any(
                o => o.OrderId == id &&
                o.Username == User.Identity.Name);

            if (isValid)
            {
                return View(id);
            }
            else
            {
                return View("Error");
            }
        }
    }
}
